// cloudfunctions/getPostDetail/index.js
const cloud = require('wx-server-sdk');
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database();
const _ = db.command;

exports.main = async (event, context) => {
  try {
    const { postId, userInfo } = event;
    console.log(userInfo);
    if (!postId) {
      return { success: false, message: '缺少postId参数' };
    }
    
    // 查询帖子详情
    const postResult = await db.collection('community_posts')
      .doc(postId)
      .get();
    
    if (!postResult.data) {
      return { success: false, message: '帖子不存在' };
    }
    
    const post = postResult.data;
    
    // 查询所有评论（包括顶级评论和回复）
    const commentsResult = await db.collection('community_comments')
      .where({ postId })
      .orderBy('createTime', 'asc')
      .get();
    
    // 构建扁平化的两级评论结构
    const comments = this.buildFlattenedTwoLevelCommentTree(commentsResult.data);
    
    // 查询点赞状态（如果已登录）
    let likeStatus = {
      post: false,
      comments: {}
    };
    
    if (userInfo) {
      // 查询帖子点赞状态
      const postLikeResult = await db.collection('user_likes')
        .where({
          userId: userInfo._id,
          type: 'post',
          itemId: postId
        })
        .get();
      console.log(postLikeResult,'点赞状态');
      likeStatus.post = postLikeResult.data.length > 0;
      
      // 查询评论点赞状态
      const commentIds = commentsResult.data.map(comment => comment._id);
      if (commentIds.length > 0) {
        const commentLikeResult = await db.collection('user_likes')
          .where({
            userId: userInfo._id,
            type: 'comment',
            itemId: _.in(commentIds)
          })
          .get();
        
        commentLikeResult.data.forEach(like => {
          likeStatus.comments[like.itemId] = true;
        });
      }
    }
    
    return {
      success: true,
      data: {
        post: {
          ...post,
          isLiked: likeStatus.post
        },
        comments: this.formatComments(comments, likeStatus.comments)
      },
      message: '获取帖子详情成功'
    };
  } catch (error) {
    console.error('获取帖子详情失败', error);
    return {
      success: false,
      message: error.message || '服务器错误',
      error: error.message
    };
  }
};

// 构建扁平化的两级评论结构（将所有评论都作为顶级评论的直接回复）
exports.buildFlattenedTwoLevelCommentTree = function(comments) {
  // 创建评论ID到评论对象的映射
  const commentMap = {};
  comments.forEach(comment => {
    commentMap[comment._id] = {
      ...comment,
      replies: []
    };
  });
  
  // 构建扁平化的树形结构
  const rootComments = [];
  
  // 首先收集所有顶级评论
  comments.forEach(comment => {
    if (!comment.replyTo) {
      rootComments.push(commentMap[comment._id]);
    }
  });
  
  // 将所有回复（无论层级）都添加到顶级评论的replies中
  comments.forEach(comment => {
    if (comment.replyTo) {
      // 查找该回复的顶级祖先评论
      const rootComment = this.findRootComment(comment, commentMap);
      if (rootComment) {
        rootComment.replies.push(commentMap[comment._id]);
      }
    }
  });
  
  return rootComments;
};

// 查找评论的顶级祖先（直接或间接回复的顶级评论）
exports.findRootComment = function(comment, commentMap) {
  let currentComment = comment;
  
  // 递归查找顶级祖先
  while (currentComment.replyTo) {
    currentComment = commentMap[currentComment.replyTo];
    if (!currentComment) {
      return null; // 找不到父评论，返回null
    }
  }
  
  return commentMap[currentComment._id];
};

// 格式化评论数据，设置点赞状态
exports.formatComments = function(comments, likeStatus) {
  return comments.map(comment => {
    // 设置当前评论的点赞状态
    comment.isLiked = likeStatus[comment._id] || false;
    
    // 设置回复评论的点赞状态
    if (comment.replies && comment.replies.length > 0) {
      comment.replies = comment.replies.map(reply => {
        reply.isLiked = likeStatus[reply._id] || false;
        return reply;
      });
    }
    
    return comment;
  });
};